package algorithm;

public class leetcode_0977 {
    public int[] sortedSquares(int[] nums) {
        int len=nums.length;
        int start=0;
        int [] list=new int[len];
        for(int i=0;i<len-1;++i){
            if(nums[i]<=0&&nums[i+1]>0) {
                if(nums[i]*nums[i]<nums[i+1]*nums[i+1]) start=i;
                else start=i+1;
            }
        }
        if(nums[len-1]<=0) start=len-1;
        if(nums[0]>=0) start=0;
        int left=start-1;
        int right=start+1;
        int current=1;
        list[0]=nums[start]*nums[start];
        while(left>=0||right<len){
            if(left<0) {
                list[current]=nums[right]*nums[right];
                current++;right++;
            }
            else if(right>=len){
                list[current]=nums[left]*nums[left];
                current++;left--;
            }else{
                if(nums[left]*nums[left]<nums[right]*nums[right]){
                    list[current]=nums[left]*nums[left];
                    current++;left--;
                }
                else{
                    list[current]=nums[right]*nums[right];
                    current++;right++;
                }
            }
        }
        return list;
    }
}
